package com.right.health.app.net;

import android.text.TextUtils;
import android.util.Log;

import com.magics.http.HttpManager;
import com.magics.http.config.HttpConnectionConfig;
import com.magics.http.constants.Method;
import com.magics.http.listener.OnHttpListener;
import com.magics.http.listener.OnHttpProgressUpdateListener;
import com.magics.http.model.HttpParams;
import com.magics.http.model.Request;
import com.magics.http.model.RequestParams;
import com.magics.http.model.Response;
import com.magics.http.parse.ParseType;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

/**
 * 网络请求基类biz
 * Created by Hope on 15/6/15.
 */
public class IBaseApi {

    private static final String REQUEST_TYPE_XML = "xml";
    private static final String REQUEST_TYPE_JSON = "json";
    private static final String REQUEST_TYPE_KEY = "request:key";

    /** 成功的网络请求标志 */
    private static final int SUCC = 0;

    /** 网络请求交互类 */
    private HttpManager mHttpManager;

    private OnHttpListener mOnHttpListener;

    /**
     * 执行异步请求
     *
     * @param rawPath 方法名
     * @param params 请求参数
     */
    public final void doGet(String rawPath, Class<?> cls, Object... params) {
        buildHeader(null);
        getHttpManager().setParseCls(ParseType.JSON, cls);
        getHttpManager().request(rawPath, params);
    }

    private void buildHeader(HttpParams params) {
        getHttpManager().setListener(mOnHttpListener);

        HttpConnectionConfig httpConnectionConfig = getHttpManager().getHttpConnectionConfig();
        httpConnectionConfig.addHeader("Content-Type", "text/xml; charset=UTF-8");
        httpConnectionConfig.addHeader("Accept", "application/json");
        httpConnectionConfig.addHeader("Content-Type", "application/x-www-form-urlencoded");
        httpConnectionConfig.setConnectionTime(60 * 1000);
    }

    protected HttpConnectionConfig getHttpConnectionConfig() {
        return getHttpManager().getHttpConnectionConfig();
    }


    /**
     * 执行异步请求
     *
     * @param rawPath 方法名
     * @param xml 请求body
     * @param cls 解析的类型
     */
    public final void doPostXml(String rawPath, String xml, Class<?> cls) {
        HttpParams params = new HttpParams();
        buildHeader(params);
        params.addFormParam("url", HttpConstants.DEFAULT_PARAM_URL);
        params.addFormParam("param", xml);
        params.addFormParam(REQUEST_TYPE_KEY, REQUEST_TYPE_XML);

        getHttpManager().setParseCls(ParseType.JSON, cls);
        getHttpManager().request(Method.POST, rawPath, params);
    }

    /**
     * 执行异步请求
     *
     * @param rawPath 方法名
     * @param params  请求body
     * @param cls     解析的类型
     */
    protected final void doPostJson(String rawPath, HttpParams params, Class<?> cls) {
        if (params == null) {
            params = new HttpParams();
        }

        buildHeader(params);
        params.addFormParam(REQUEST_TYPE_KEY, REQUEST_TYPE_JSON);

        getHttpManager().setParseCls(ParseType.JSON, cls);
        getHttpManager().request(Method.POST, rawPath, params);
    }


    /**
     * 执行异步请求
     *
     * @param rawPath 方法名
     * @param params 请求body
     * @param cls 解析的类型
     */
    public final void doUpload(String rawPath, HttpParams params, Class<?> cls) {
        getHttpManager().setListener(mOnHttpListener);
        getHttpManager().setParseCls(ParseType.JSON, cls);
        getHttpManager().request(Method.POST, rawPath, params);
    }

    /**
     * 执行异步请求
     * @param l 下载监听
     * @param rawPath 请求地址
     * @param fileDir 存储路径
     */
    public final void doLoadFile(OnHttpProgressUpdateListener l, String rawPath, String fileDir) {
        doLoadFile(l, rawPath, fileDir, null);
    }

    /**
     * 执行异步请求
     * @param l 下载监听
     * @param rawPath 请求地址
     * @param fileDir 存储路径
     */
    private void doLoadFile(OnHttpProgressUpdateListener l, String rawPath, String fileDir, String fileName) {
        getHttpManager().setListener(mOnHttpListener);
        getHttpManager().setHttpProgressUpdateListener(l);
        getHttpManager().downloadFile(rawPath, fileDir, fileName);
    }

    /**
     * 获取mHttpManager对象
     * @return HttpManager
     */
    private HttpManager getHttpManager(){
        if(mHttpManager == null){
            mHttpManager = new HttpManager() {

                @Override
                public void onPreExecute(Request request) {

                }

                private void parseJson(Response response) throws JSONException {
                    if(response != null && !TextUtils.isEmpty(response.data)) {
                        JSONObject root = new JSONObject(response.data);
                        if(!root.isNull("appStatus")) {
                            JSONObject appStatus = root.getJSONObject("appStatus");
                            if(!appStatus.isNull("errorCode")) {
                                String errorCode = appStatus.getString("errorCode");
                                String msg = appStatus.getString("msg");

                                if("00".equals(errorCode)) { //成功
                                    response.data = root.toString();
                                } else {
                                    response.responseCode = 500;
                                    response.error = msg;
                                }
                            }
                        } else {
                            response.responseCode = 500;
                            response.error = "系统繁忙";
                        }
                    }
                }

                @Override
                public Response parseResponse(RequestParams requestParams, Response response) throws JSONException {
                    Log.e("TAG", "request url = " + requestParams.requestUrl +" ,request params = "+requestParams.httpParams);
                    Log.e("TAG",  "responseCode = " + response.responseCode + ",data = " + response.data);
                    if(requestParams.request.httpParams != null) {
                        Map<String, String> formParams =  requestParams.request.httpParams.getFormParams();
                        String requestType = formParams.get(REQUEST_TYPE_KEY);

                        if(REQUEST_TYPE_JSON.equals(requestType)) {
                            parseJson(response);
                        }
                    }

                    return response;
                }

                @Override
                public void onPostExecute(Request request, Response response) {

                }
            };
        }
        return mHttpManager;
    }

    /**
     * 为本次请求添加一个requestCode
     * @param requestCode 请求编号
     */
    public void addRequestCode(int requestCode) {
        getHttpManager().addRequestCode(requestCode);
    }

    /**
     * 为本次请求添加一个tag
     * @param tag 请求tag
     */
    public void setTag(Object tag) {
        getHttpManager().setTag(tag);
    }

    /**
     * 设置监听
     * @param onHttpListener 回调监听
     */
    public void setListener(OnHttpListener onHttpListener){
        this.mOnHttpListener = onHttpListener;
    }
}
